package com.atosworldline.tfm.model;

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import org.codehaus.jackson.annotate.JsonIgnore;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;
import java.lang.reflect.Field;
import javax.persistence.Column;
import javax.xml.bind.annotation.XmlTransient; 

import java.io.Serializable;
import java.io.IOException;

import com.atosworldline.tfm.service.DocumentService;
import com.atosworldline.tfm.service.DocumentServiceImpl;

@Entity
@XmlRootElement
public class Document implements Serializable{

	private Long _id;
	private HashMap _parameter=new HashMap();

	public Document() {
		super();
	}
	
	@Id
		@GeneratedValue
		public Long getId() {
			return _id;
		}

	public void setId(Long id) {
		this._id = id;
	}

	/**
	 * @return the parameter
	 */
	@XmlTransient
	@JsonIgnore 
	@Column(length=1024)
	public HashMap getParameter() {
		//		_parameter.clear();	

		_parameter.put("id",this.getId());

		for(Field field : this.getClass().getDeclaredFields()){
			try{
				if(field.getName().indexOf("_")!=0 ){
						_parameter.put(field.getName(), field.get(this));
				}
			}catch(java.lang.IllegalAccessException e){
				_parameter.put(field.getName(), null);
			}
		}

		return _parameter;
	}

	/**
	 * @param name the parameter to set
	 */
	public void setParameter(HashMap parameter) {
		this._parameter = parameter;

		List<String> fields= new ArrayList();
		for(Field field : this.getClass().getDeclaredFields()){
			try{
				if(parameter.keySet().contains(field.getName())){
						field.set(this, parameter.get(field.getName()));
				}	
			}catch(java.lang.IllegalAccessException e){
				_parameter.put(field.getName(), null);
			}
		}
	}

	public String toString(){
		return super.toString()+"id :"+this.getId();
	}

	private void writeObject(java.io.ObjectOutputStream out) throws IOException{
		if(this.getId()!=null){
			out.writeLong(this.getId());
		}else{
			DocumentService service = DocumentServiceImpl.getDocumentService();
			Document doc = service.create(this);		
			out.writeLong(doc.getId());
		}
	}

	private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{
		if(in.available()>=8){this.setId(in.readLong());};
	}
}
